var createError = require('http-errors');    //http-errors 记录http异常
var express = require('express');    //express 包含API
var path = require('path');       //  node里自带的模块
var cookieParser = require('cookie-parser');   //处理cookie
var logger = require('morgan');         //记录服务器的日志

//路由的配置文件
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var commentRouter = require('./routes/comment');

var vueRouter = require('./routes/vue')

var connection = require('./utils/connect')
var app = express();
//服务器用来保存用户登录后记录的相关信息
var session = require('express-session')

var cors = require('cors')

app.use(cors())  //裸奔，为所有人敞开，都可以访问接口


// view engine setup
//path.join  拼接  设置项目试图文件目录 __dirname 根目录 views重置根目录
app.set('views', path.join(__dirname, 'views'));  
app.set('view engine', 'ejs');  //设置模板引擎

app.use(logger('dev'));   //日志记录中间件
app.use(express.json());   //****** 处理post请求提交的参数的  application/json  json格式*/
app.use(express.urlencoded({ extended: false }));    //post  application/x-www-urlencoded 字符串
app.use(cookieParser());   //处理cookie
app.use(express.static(path.join(__dirname, 'public')));  //express.static 设置项目的静态文件目录  以文件名读取  吧public 重置到根目录

// app.use(function(req,res,next){
//   console.log('this is first middleware...');
//   next()
// })

// session 中间件  必须写在路由中间件前面  (用来保存用户登录后的所有数据)
app.use(session({
  name:"AppTest",
  cookie:{maxAge:1000*60*60*60},  // session 时长
  secret:"test",
  resave:false,
  saveUninitialized:true
}))






//设置路由的中间键
app.use('/', indexRouter);      // / 路由别名 区别每个路由模块
app.use('/users', usersRouter);  //  users  路由别名 区别每个路由模块
app.use('/comment', commentRouter);
app.use('/vue',vueRouter)

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);   //500  服务器异常
  res.render('error');      //res.render  渲染 ejs 模板
});

module.exports = app;
